import { defineStore } from 'pinia'
import type { RouteRecordRaw } from 'vue-router'
import router from '@/router'
import Layouts from '@/layouts/default/index.vue'

import type { UserInfo } from '#/login'
import type { MenuItem, RoleItem, RoleChildrenItem } from '#/system'
import { getUserMenus } from '@/api/system/user'
const modules = import.meta.glob('@/views/**/*.vue')

export const useUserStore = defineStore('user', {
  state: () => ({
    systemType: '', // 默认类型
    currentPath: '', // 当前路由
    menuOpenKeys: [] as string[], // 菜单当前打开值
    token: '', // 用户token
    userInfo: {
      id: 0,
      name: '',
      username: '',
      type: ''
    }, // 用户信息
    currentMenus: [] as MenuItem[],
    homeMenu: '/overview/index'
  }),
  getters: {
    getCurrentPath(): string {
      return this.currentPath
    },
    getToken(): string {
      return this.token
    },
    getUserInfo(): UserInfo {
      return this.userInfo
    },
    getSystemType(): string {
      return this.systemType
    },
    getMenuOpenKeys(): string[] {
      return this.menuOpenKeys
    },
    getCurrentMenus(): MenuItem[] {
      return this.currentMenus
    },
    getHomeMenu(): String {
      return this.homeMenu
    }
  },
  actions: {
    setCurrentPath(currentPath: string) {
      this.currentPath = currentPath
    },
    setToken(token: string) {
      this.token = token
    },
    setUserInfo(userInfo: UserInfo) {
      this.userInfo = userInfo
    },
    setSystemType(systemType: string) {
      this.systemType = systemType
    },
    setMenuOpenKeys(menuOpenKeys: string[]) {
      this.menuOpenKeys = menuOpenKeys
    },
    setHomeMenu(homeMenu: string) {
      this.homeMenu = homeMenu
    },
    // 默认的路由配置
    getDefaultSystemRouters() {
      const defaultSystemRouters: RoleItem[] = [
        {
          name: 'overview',
          path: '/overview',
          title: '概览',
          component: 'Layouts',
          redirect: '/overview/index',
          menu: false,
          children: [
            {
              name: 'overview',
              path: 'index',
              icon: 'home',
              component: '/src/views/overview/index.vue',
              title: '概览'
            }
          ]
        }
      ]
      return defaultSystemRouters
    },
    // 获取用户有权限的菜单
    getUserRoles() {
      const userRoles: RoleItem[] = this.getDefaultSystemRouters()
      const userMenus: RoleItem[] = []
      for (const menuItem of this.currentMenus) {
        const roleItem = userRoles.find((roleItem) => roleItem.title === menuItem.label)
        if (roleItem) {
          if (roleItem.children.length === 1) {
            userMenus.push(roleItem)
          } else {
            const childLabelList = menuItem.children?.map((a: { label: string }) => a.label) || []

            const newRoleItem = {
              ...roleItem,
              children: roleItem.children.filter((a) => childLabelList.includes(a.title))
            }
            if (newRoleItem.children.length > 0) userMenus.push(newRoleItem)
          }
        }
      }
      return userMenus
    },
    // 获取用户操作权限列表
    getUsersActionRoles() {
      const userRoles: RoleItem[] = this.getDefaultSystemRouters()
      const userMenuRoles: string[] = []
      for (const menuItem of this.currentMenus) {
        const roleItem = userRoles.find((roleItem) => roleItem.title === menuItem.label)
        if (roleItem) {
          if (roleItem.children.length === 1) {
            const newRoleItems = menuItem.children?.map((c) => `${roleItem.title}:${c.label}`) || []
            userMenuRoles.push(...newRoleItems)
          } else {
            const childLabelList = menuItem.children?.map((a: { label: string }) => a.label) || []
            const newRoleItem = {
              ...roleItem,
              children: roleItem.children.filter((a) => childLabelList.includes(a.title))
            }
            for (const item of newRoleItem.children) {
              const findChildMenu = menuItem.children?.find((b) => b.label === item.title)
              const newRoleItems =
                findChildMenu?.children?.map((c) => `${item.title}:${c.label}`) || []
              userMenuRoles.push(...newRoleItems)
            }
          }
        }
      }
      return userMenuRoles
    },
    // 获取权限列表是否
    getPermissionStatus(permissionList: string[] = []) {
      let status = false
      const userRoleList = this.getUsersActionRoles()
      for (const permission of permissionList) {
        if (userRoleList.includes(permission)) {
          status = true
          break
        }
      }
      return status
    },
    async afterLoginAction() {
      const menuList = await getUserMenus()
      this.setCurrentMenus(menuList.data || [])
      const userRoles = this.getUserRoles()
      if (userRoles.length > 0 && userRoles[0].children.length > 0) {
        const homeMenu = `${userRoles[0].path}/${userRoles[0].children[0].path}`
        this.setHomeMenu(homeMenu)
      }
      for (const roleItem of userRoles) {
        const routeItem: RouteRecordRaw = {
          path: roleItem.path,
          name: roleItem.name,
          component: this.getComponent(roleItem.component),
          children: roleItem.children.map((child: RoleChildrenItem) => {
            const item: RouteRecordRaw = {
              path: child.path,
              name: child.name,
              meta: {
                title: child.title
              },
              component: this.getComponent(child.component)
            }
            return item
          })
        }
        router.addRoute(routeItem)
      }
    },
    // 登出
    logout(redirectFlag = false) {
      this.clearLogInfo()
      if (redirectFlag) {
        router.push({
          path: '/login',
          query: {
            redirect: router.currentRoute.value.fullPath
          }
        })
      } else {
        router.push({
          path: '/login'
        })
      }
    },
    clearLogInfo() {
      this.token = ''
      this.userInfo = { id: 0, name: '', username: '', type: '' }
    },
    setCurrentMenus(currentMenus: MenuItem[]) {
      this.currentMenus = currentMenus
    },
    getComponent(component: string) {
      return component === 'Layouts' ? Layouts : modules[component]
    }
  },
  persist: true
})
